<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\kuaishou;

use app\command\BaseWork;
use app\enum\CommonEnum;
use app\model\ClientModel;
use app\model\mongo\MongoKsUserVideoModel;
use app\model\mongo\MongoKsVideoDayReportModel;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class KsProductVideoCostWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('ks_product_video_cost_work');
        $this->setDescription('快手客户产品消耗数据汇总');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $this->getOutputMessage('快手客户产品消耗数据汇总开始');
        try {
            $products = Db::name('client_promotion_product')
                ->where('media_id', CommonEnum::KS_MEDIA)
                ->field('id,client_id,product_name')
                ->group('id')
                ->order('id desc')
                ->select();
            foreach ($products as $v) {
                $clientName = (new ClientModel())->where('id', $v['client_id'])->value('client_short_name');
                $data = [
                    'product_id' => $v['id'],
                    'client_id' => $v['client_id'],
                    'product_name' => $v['product_name'],
                    'client_name' => $clientName,
                ];
                $videoAccount = Db::name('advertiser_bind_product')->alias('a')
                    ->leftJoin(['habo_client_account' => 'b'], 'a.advertiser_id=b.advertiser_id')
                    ->where('a.product_id', $v['id'])
                    ->group('b.id')
                    ->column('b.id');
                $data['cost'] = 0;
                $data['sz_cost'] = 0;
                $data['cost_ninety'] = 0;
                $data['sz_cost_ninety'] = 0;
                $endDate = [];
                $videoType = [];
                $page = 0;
                $limit = 10000;
                while (true) {
                    $start = $page == 0 ? 0 : $page * $limit - 1;
                    $videoData = (new MongoKsVideoDayReportModel())
                        ->whereIn('account_id', $videoAccount)
                        ->field('stat_date,cost,video_id')
                        ->limit($start, $limit)
                        ->select()->toArray();
                    if (empty($videoData)) {
                        break;
                    }
                    foreach ($videoData as $val) {
                        if (empty($val['video_id'])) {
                            continue;
                        }
                        if (! isset($endDate[$val['video_id']])) {
                            $startDate = date('Y-m-d', strtotime(strval($val['stat_date'])));
                            $endDate[$val['video_id']] = date('Ymd', strtotime($startDate . '+90 days'));
                        }
                        if (! isset($videoType[$val['video_id']])) {
                            $video = (new MongoKsUserVideoModel())->where('photo_id', $val['video_id'])->field('source')->find();
                            $videoType[$val['video_id']] = $video['source'] ?? '';
                        }
                        if ($videoType[$val['video_id']] != 2) {
                            // 非素造
                            $data['cost'] += $val['cost'];
                            if ($val['stat_date'] <= $endDate[$val['video_id']]) {
                                $data['cost_ninety'] += $val['cost'];
                            }
                        } else {
                            // 素造
                            $data['sz_cost'] += $val['cost'];
                            if ($val['stat_date'] <= $endDate[$val['video_id']]) {
                                $data['sz_cost_ninety'] += $val['cost'];
                            }
                        }
                    }
                    ++$page;
                }
                unset($videoData);
                $data['all_cost'] = $data['cost'] + $data['sz_cost'];
                $data['all_cost_ninety'] = $data['cost_ninety'] + $data['sz_cost_ninety'];
                $isHas = Db::name('client_ks_video_cost_data')->where('client_id', $v['client_id'])
                    ->where('product_id', $v['id'])
                    ->find();
                if ($isHas) {
                    $res = Db::name('client_ks_video_cost_data')->where('id', $isHas['id'])->update($data);
                    if ($res) {
                        $this->getOutputMessage($v['product_name'] . '更新成功');
                    }
                } else {
                    $res = Db::name('client_ks_video_cost_data')->create($data);
                    if ($res) {
                        $this->getOutputMessage($v['product_name'] . '新增成功');
                    }
                }
            }
        } catch (\Exception $e) {
            dd($e);
            $this->getOutputMessage('快手客户产品消耗数据汇总失败:' . $e->getMessage());
        }
        $this->getOutputMessage('快手客户产品消耗数据汇总结束');
    }
}
